package com.cloudcross.ssp.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class AliYunOSSOperator {

    private static Properties properties;
    static {
        properties = new Properties();
        InputStream in = AliYunOSSOperator.class.getResourceAsStream("/application.properties");
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final String accessKeyId = properties.getProperty("accessKeyId");
    private static final String accessKeySecret = properties.getProperty("accessKeySecret");
    private static final String endPoint = properties.getProperty("endPoint");
    private static final String defaultBucketName = properties.getProperty("bucketName");
    private static OSSClient client = new OSSClient(endPoint, accessKeyId, accessKeySecret);
    private static Logger logger = LogManager.getLogger(AliYunOSSOperator.class);

    private static Bucket findExistBucketByName(String bucketName) {
        List<Bucket> buckets = client.listBuckets();
        for (Bucket buck : buckets) {
            if (buck.getName().equalsIgnoreCase(bucketName)) {
                client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                return buck;
            }
        }
        return null;
    }

    @SuppressWarnings("unused")
    private static Bucket getBucketByName(String bucketName) {
        boolean exists = client.doesBucketExist(bucketName);
        if (exists) {
            return findExistBucketByName(bucketName);
        } else {
            Bucket bucket = client.createBucket(bucketName);
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            logger.info(" Bucket created with name -> " + bucket.getName());
            return bucket;
        }
    }

    /**
     * client.putObject(defaultBucketName, key, content, meta);
     * key【要上传的对象在服务器上的名称】 : Object名称在使用UTF-8编码后长度必须在
     * 1-1023字节之间，而且不能包含回车、换行、以及xml1.0不支持的字符，同时也不能以“/”或者“\”开头。
     * 
     * @param key
     * @param filePath
     */
    public static void saveObject(String key, String filePath) {
        String filePrefix = "dsp/";
        key = filePrefix + key;
        File file = new File(filePath);
        InputStream content = null;
        try {
            content = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.error(" File not found. " + e);
        }
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.length());
        PutObjectResult result = client.putObject(defaultBucketName, key, content, meta);
        logger.info(" Save object result -> " + result.getETag());
    }

    public static void copy(String okey, String ckey) {
        client.copyObject(defaultBucketName, okey, defaultBucketName, ckey);
        logger.info(" Bucket copy with name -> " + okey);
    }

    public static void main(String[] args) {
        AliYunOSSOperator.saveObject("upload/banner/business_license.jpg", "C:\\Users\\thinkpad\\Desktop\\240-480.jpg");
        logger.info(" Ali yun OSS object saved.");
    }
}
